<template>
  <el-card class="filter-card">
    <el-row :gutter="24" align="middle">
      <el-col :span="6">
        <el-input v-model="searchQuery" placeholder="搜索描述..." @keyup.enter="refreshOrders" clearable />
          </el-col>
          <el-col :span="4">
        <el-select v-model="statusFilter" placeholder="状态筛选" clearable>
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-col>
          <el-col :span="4">
        <el-select v-model="typeFilter" placeholder="类型筛选" clearable>
          <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="refreshOrders">
          <el-icon><Refresh/></el-icon> 刷新
            </el-button>
          </el-col>
        </el-row>
      </el-card>

  <!-- 工单表格 -->
  <el-card class="table-card" style="margin-top: 16px">
        <el-table :data="repairOrders" stripe style="width: 100%" :loading="loading">
          <el-table-column prop="id" label="单号" width="170"/>
      <el-table-column prop="title" label="标题" min-width="150" />
          <el-table-column prop="des" label="问题描述" min-width="200" />
          <el-table-column prop="type" label="类型" width="100">
            <template #default="{ row }">
              <el-tag :type="getTypeTagType(row.type)">{{ getTypeText(row.type) }}</el-tag>
            </template>
          </el-table-column>
      <el-table-column label="房间号" width="120">
        <template #default="{ row }">
          {{ roomMap[row.roomId] || row.roomId }}
        </template>
      </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)">{{ getStatusText(row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="160"/>
      <el-table-column label="操作" width="210">
            <template #default="{ row }">
          <el-button size="small" type="primary" text @click="viewOrder(row)">查看</el-button>
          <el-button size="small" type="success" text @click="editOrder(row)">编辑</el-button>
          <el-button size="small" type="danger" text @click="deleteOrder(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="totalOrders"
          :page-sizes="[10,20,50,100]"
          layout="total, sizes, prev, pager, next, jumper"
          background
      style="margin-top: 12px;"
        />
      </el-card>

  <!-- 编辑工单 -->
  <el-dialog v-model="editVisible" title="编辑工单" width="600px" @close="resetEditForm">
    <el-form :model="editForm" label-width="90px">
      <el-form-item label="单号">
        <el-input v-model="editForm.id" disabled />
      </el-form-item>
      <el-form-item label="标题">
        <el-input v-model="editForm.title" />
      </el-form-item>
      <el-form-item label="问题描述">
        <el-input v-model="editForm.des" />
      </el-form-item>
      <el-form-item label="维修类型">
        <el-select v-model="editForm.type">
          <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="editForm.status">
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="楼栋">
        <el-select v-model="editForm.buildingId" placeholder="选择楼栋" @change="onEditBuildingChange" style="width:100%">
          <el-option v-for="build in editBuildingList" :key="build.id" :label="build.name" :value="build.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="房间号">
        <el-select v-model="editForm.roomId" placeholder="请选择房间" :disabled="!editForm.buildingId" filterable style="width:100%">
          <el-option v-for="room in editRoomList" :key="room.id" :label="room.roomNumber" :value="room.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="预约时间">
        <el-date-picker v-model="editForm.orderTime" type="datetime" placeholder="选择日期时间" style="width: 100%" />
      </el-form-item>
      <el-form-item label="维修人员">
        <el-select v-model="editForm.maintainerId" placeholder="选择维修员" filterable style="width:100%">
          <el-option v-for="m in maintainerList" :key="m.id" :label="m.name || m.username || m.id" :value="m.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="联系方式">
        <el-input v-model="editForm.phone" />
      </el-form-item>
    </el-form>
      <template #footer>
      <el-button @click="editVisible = false">取消</el-button>
      <el-button type="primary" @click="saveEditOrder" :loading="editLoading">保存</el-button>
      </template>
    </el-dialog>

  <!-- 工单详情弹窗 -->
  <el-dialog v-model="viewVisible" title="工单详情" width="700px">
    <el-descriptions :column="2" border title="基本信息">
      <el-descriptions-item label="单号">{{ viewOrderData.id || '-' }}</el-descriptions-item>
      <el-descriptions-item label="标题">{{ viewOrderData.title || '-' }}</el-descriptions-item>
      <el-descriptions-item label="学号">{{ viewOrderData.studentId || '-' }}</el-descriptions-item>
      <el-descriptions-item label="联系电话">{{ viewOrderData.phone || '-' }}</el-descriptions-item>
      <el-descriptions-item label="预约时间">{{ viewOrderData.orderTime || viewOrderData.reserveTime || '-' }}</el-descriptions-item>
      <el-descriptions-item label="创建时间">{{ viewOrderData.createTime || '-' }}</el-descriptions-item>
      <el-descriptions-item label="更新时间">{{ viewOrderData.updateTime || '-' }}</el-descriptions-item>
    </el-descriptions>
    <el-descriptions :column="2" border title="房间与维修">
      <el-descriptions-item label="楼栋">{{ viewOrderData.buildingName || '-' }}</el-descriptions-item>
      <el-descriptions-item label="房间号">{{ roomMap[viewOrderData.roomId] || viewOrderData.roomNumber || viewOrderData.roomId || '-' }}</el-descriptions-item>
      <el-descriptions-item label="类型">
        <el-tag :type="getTypeTagType(viewOrderData.type)">{{ getTypeText(viewOrderData.type) }}</el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="状态">
        <el-tag :type="getStatusTagType(viewOrderData.status)">{{ getStatusText(viewOrderData.status) }}</el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="维修员">
        <span>{{ viewOrderData.maintainerName || viewOrderData.maintainerId || '-' }}</span>
      </el-descriptions-item>
    </el-descriptions>
    <el-descriptions :column="1" border title="问题描述">
      <el-descriptions-item label="问题描述">
        <el-collapse>
          <el-collapse-item name="problem-des">
            <template #title>
              <span>{{ (viewOrderData.des && viewOrderData.des.length > 50) ? (showFullDes ? viewOrderData.des : (viewOrderData.des.slice(0,50) + '...')) : viewOrderData.des }}</span>
              <el-button v-if="viewOrderData.des && viewOrderData.des.length > 50" text type="primary" @click="showFullDes = !showFullDes" style="margin-left: 10px;">
                {{ showFullDes ? '收起' : '展开' }}
              </el-button>
            </template>
            <div>{{ viewOrderData.des }}</div>
          </el-collapse-item>
        </el-collapse>
      </el-descriptions-item>
      <el-descriptions-item label="图片">
        <template v-if="viewOrderData.pic">
          <el-image style="width: 60px; height: 60px;cursor:pointer" :src="viewOrderData.pic" fit="cover" :preview-src-list="[viewOrderData.pic]" preview-teleported />
        </template>
        <template v-else>-</template>
      </el-descriptions-item>
    </el-descriptions>
    <el-descriptions :column="2" border title="用户评价" v-if="viewOrderData.star || viewOrderData.content">
      <el-descriptions-item label="评价星级">
        <el-rate v-if="viewOrderData.star" v-model="viewOrderData.star" disabled show-score score-template="{value}" />
      </el-descriptions-item>
      <el-descriptions-item label="评价内容">{{ viewOrderData.content || '-' }}</el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <el-button @click="viewVisible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh} from '@element-plus/icons-vue'
import { fetchOrderAPI, deleteOrderAPI, updateOrderAPI } from '@/apis/orderAPI'
import { queryRoomAPI } from '@/apis/roomAPI'
import { queryDormBuild } from '@/apis/roomBuildAPI'
import { queryMaintainerAPI } from '@/apis/maintainerAPI'

// 查询条件及分页
const searchQuery = ref('')
const statusFilter = ref('')
const typeFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

const repairOrders = ref([])
const totalOrders = ref(0)
const loading = ref(false)

// 房间号映射
const roomMap = ref({})

// 详情弹窗相关
const viewVisible = ref(false)
const viewOrderData = ref({})
const showFullDes = ref(false) // 长描述展开/收起

// 类型、状态选项
const typeOptions = [
  { value: 0, label: '水电故障' },
  { value: 1, label: '家具损坏' },
  { value: 2, label: '网络维修' }
]
const statusOptions = [
  { value: 0, label: '待处理' },
  { value: 1, label: '处理中' },
  { value: 2, label: '已完成' }
]

// tag颜色映射方法
const defaultTypeMap = { 0: 'primary', 1: 'success', 2: 'info' }
const defaultStatusMap = { 0: 'warning', 1: 'info', 2: 'success' }
function getTypeTagType(type) {
  return defaultTypeMap[type] || 'info'
}
function getStatusTagType(status) {
  return defaultStatusMap[status] || ''
}
function getTypeText(type) {
  const obj = typeOptions.find(o => o.value === type)
  return obj ? obj.label : type
}
function getStatusText(status) {
  const obj = statusOptions.find(o => o.value === status)
  return obj ? obj.label : status
}

// 拉取房间号映射
async function fetchRoomMap() {
  try {
    const res = await queryRoomAPI({ pageNum: 1, pageSize: 999 })
    const list = res.data?.records || res.data || []
    list.forEach(room => {
      roomMap.value[room.id] = room.roomNumber
    })
  } catch (e) {
    ElMessage.error('获取房间信息失败')
  }
}

// 拉取工单
async function fetchOrders() {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      search: searchQuery.value,
      status: statusFilter.value,
      type: typeFilter.value
    }
    const res = await fetchOrderAPI(params)
    repairOrders.value = res.data?.records || res.data || []
    totalOrders.value = res.data?.total || (res.data?.records ? res.data.total : 0)
  } catch (e) {
    ElMessage.error('获取工单失败')
  } finally {
    loading.value = false
  }
}

function refreshOrders() {
  currentPage.value = 1
  fetchOrders()
}

// 操作区
function viewOrder(row) {
  viewOrderData.value = { ...row }
  viewVisible.value = true
}
const editVisible = ref(false)
const editForm = ref({})
const editLoading = ref(false)
const editBuildingList = ref([])
const editRoomList = ref([])
const maintainerList = ref([])

async function loadMaintainers() {
  const res = await queryMaintainerAPI()
  maintainerList.value = res.data || []
}

// 编辑弹窗楼栋变化时拉房间数据
async function onEditBuildingChange(bid) {
  editForm.value.roomId = ''
  if (!bid) {
    editRoomList.value = []
    return
  }
  const res = await queryRoomAPI({ buildingId: bid, pageNum: 1, pageSize: 100 })
  editRoomList.value = res.data?.records || res.data || []
}

// 编辑弹窗打开时初始化（自动带出楼栋&房间&房间列表）
async function editOrder(row) {
  editForm.value = { ...row }
  const buildRes = await queryDormBuild()
  editBuildingList.value = buildRes.data || []
  // 默认拉全部房间
  const allRoomRes = await queryRoomAPI({ pageNum: 1, pageSize: 999 })
  editRoomList.value = allRoomRes.data?.records || allRoomRes.data || []
  let currentBid = row.buildingId
  if (!currentBid && row.roomId) {
    const singleRoom = (await queryRoomAPI({ id: row.roomId })).data?.records?.[0]
    currentBid = singleRoom?.buildingId || ''
    editForm.value.buildingId = currentBid
  }
  if (editForm.value.buildingId) {
    await onEditBuildingChange(editForm.value.buildingId)
  }
  await loadMaintainers()
  editVisible.value = true
}
async function saveEditOrder() {
  editLoading.value = true
  try {
    await updateOrderAPI(editForm.value)
    ElMessage.success('编辑成功')
    editVisible.value = false
    fetchOrders()
  } catch (e) {
    ElMessage.error('编辑失败')
  } finally {
    editLoading.value = false
  }
}
function resetEditForm() {
  editForm.value = {}
}
async function deleteOrder(row) {
  try {
    await ElMessageBox.confirm('此操作将永久删除该工单，是否继续？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await deleteOrderAPI(row.id)
    ElMessage.success('删除成功')
    fetchOrders()
  } catch (e) {
    // 判断是取消还是错误
    if (e !== 'cancel' && e !== 'close') {
      ElMessage.error('删除失败')
    }
  }
}

// 联动分页
watch([currentPage, pageSize], fetchOrders)

onMounted(() => {
  fetchRoomMap()
  fetchOrders()
})
</script>

<style scoped>
.filter-card {
  margin-bottom: 12px;
}
.table-card {
  min-height: 240px;
}
.room-number {
  color: #409EFF;
}
</style>
